package com.kk.loadtext;

import com.kk.utils.AdvanceThreadPool;
import org.json.simple.JSONObject;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Logger;

/**
 * @author 王志强
 * @date 2021-12-02
 * description: 长连接传输数据
 */
public class Client {
    private final Logger logger = (Logger) LoggerFactory.getLogger(Client.class);
    private OutputStreamWriter outputStreamWriter;
    private Socket socket;

    public Client() throws IOException {
        try {
            socket = new Socket("127.0.0.1", 8888);
            socket.setSoTimeout(3);
            AdvanceThreadPool.poolExecutor.submit(new ClientSend());

        } catch (IOException e) {
            logger.info(e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
    }

    /**
     * 专用于客户端传输数据
     */
    class ClientSend implements Runnable {
        @Override
        public void run() {
            try {
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());

                while (true) {
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("请输入: ");
                    String s = scanner.nextLine();
                    JSONObject object = new JSONObject();
                    object.put("code", "0");
                    object.put("msg", "success");
                    object.put("input", s);
                    outputStream.writeObject(object);
                    outputStream.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    logger.info("关闭失败");
                }
            }
        }
    }
}
